# photomanager.py
import os
import logging
import util
from pysage import Actor, ActorManager
from models.album import Album
from persistence import dbtransaction
from messages import *

omanager = ActorManager.get_singleton()

class ResourceParser(Actor):
    subscriptions = ['InitializeAlbumsDataMessage']
    def __init__(self):
        Actor.__init__(self)
        self.albums = {}
    @dbtransaction
    def handle_InitializeAlbumsDataMessage(self, msg):
        '''this method imports all locally registered folders, as well as user defined virtual foldes (albums)
            and loads them to the photo data manager
        '''
#        map(lambda x: self.load_album(x), omanager.find('mapi').get_albums())
        return True
    @property
    def images(self):
        photos = {}
        for a in self.albums.values():
            photos.update(a.images)
        return photos
    def get_image(self, imageid):
        for a in self.albums.values():
            if a.images.has_key(imageid):
                return a.images[imageid]
        return None
#    def load_album(self, p):
#        '''import just one folder'''
#        images = util.filter_files([os.path.join(p.path, x) for x in os.listdir(p.path)])
#        if images:
#            album = self.cache_album(p)
#            for f in images:
#                album.add_image(f)
    @dbtransaction
    def batch_import_path(self, path):
        '''import folder and all subfolders, 
            returns a list of path that was imported'''
        for root, dirs, files in os.walk(path):
            if root == path:
                files = util.filter_files([os.path.join(root, x) for x in files])
                if files:
                    album = omanager.find('mapi').add_album(root)
                    for f in files:
                        album.add_image(f)
                    return True
        return False
        # omanager.find('container').cmd.SetValue('''python main.py "%s" home 127.0.0.1 8081''' % path)
        # omanager.find('container').photos_viewer.set_album(omanager.find('mapi').get_albums()[0])
#    def cache_album(self, p):
#        '''creates an album, store it and return it'''
#        return Album(p.path)

